package com.ioc;

import lombok.AllArgsConstructor;

import java.lang.reflect.Field;

/**
 * @author SaErNuoSi
 * @date 2018/4/18 9:36
 */
public class DefaultInject implements InjectInterface {

    private IOC ioc;
    private Field field;

    public DefaultInject(IOC ioc, Field field) {
        this.ioc = ioc;
        this.field = field;
    }

    @Override
    public void inject(Object object) {
        Class<?> type = field.getType();
        Object bean = ioc.getBean(type);
        if (bean == null) {
            throw new IllegalStateException("Can't inject bean: " + type.getName() + " for field: " + field);
        }
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            field.set(object, bean);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            field.setAccessible(accessible);
        }

    }
}
